local cjson = require "cjson"
local amqp = require "amqp"
local kong = kong

local HeaderSendToRabbitMQ = {}

local function init_client(plugin_conf)
    local client, err = amqp.new({
        role = "publisher", 
        ssl = false, 
        user = plugin_conf.rabbitmq_username,
        password = plugin_conf.rabbitmq_password,
        exchange = plugin_conf.rabbitmq_exchange,        
        virtual_host = plugin_conf.rabbitmq_vhost,
        routing_key = plugin_conf.rabbitmq_routing_key,
    })

    if not client then
        kong.log.err("failed to create RabbitMQ client: ", err)
        return nil, err
    end

    local ok, err = client:connect(plugin_conf.rabbitmq_host, plugin_conf.rabbitmq_port)
    if not ok then
        kong.log.err("failed to connect to RabbitMQ: ", err)
        return nil, err
    end

    client:setup()    
    return client
end

function HeaderSendToRabbitMQ:rewrite(plugin_conf)
    -- 写入日志
    kong.log.notice("start send header to rabbitmq----------------")

    -- 获取或初始化AMQP客户端
    local mq_client, err = init_client(plugin_conf)
    if not mq_client then
        return
    end

    -- 获取请求头数据
    local headers = kong.request.get_headers()
    local headers_json = cjson.encode(headers)

    local ok, err = mq_client:publish(headers_json)
    mq_client:close()
    
    if not ok then
        kong.log.err("Failed to publish message: ", err)
    else
        kong.log.notice("Successfully published message")
    end
end

return HeaderSendToRabbitMQ